import axios from 'axios'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url

})

// 请求拦截器 发送请求自动添加token
service.interceptors.request.use(config => {
  // console.log('所有的请求都要经过我这里', config)
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function(error) {
  return Promise.reject(error)
})

// 响应拦截器 所有的响应都会过来
service.interceptors.response.use(response => {
  // console.log('所有滴响应都会经过这里滴', response)
  if (!response.data.success) {
    return Promise.reject(response.data.message)
  }
  return response.data
}, function(error) {
  // console.log('错误', error.response)
  if (error.response.status === 401 && error.response.data.code === 10002) {
    store.dispatch('user/delUserInfo')
    router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
  }
  return Promise.reject(error)
})

export default service
